package com.zaofan.service;

import com.google.gson.Gson;
import com.zaofan.bean.Product;
import com.zaofan.bean.ProductAttr;
import com.zaofan.bean.QualityExtend;
import com.zaofan.bean.ResultProduct;
import com.zaofan.bean.Shop;
import com.zaofan.bean.ShopCategory;
import com.zaofan.cache.CacheManage;
import com.zaofan.constant.StateConstant;
import com.zaofan.constant.UrlConstant;
import com.zaofan.dao.ProductDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.mobile.bean.ProductResult;
import com.zaofan.mobile.bean.ProductResultV2;
import com.zaofan.service.remote.RemoteService;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.springframework.util.Assert;
import sun.rmi.runtime.Log;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProductService {
	private RemoteService remoteService = new RemoteService();
	private ProductDao productDao = new ProductDao();
	private ShopService shopService = new ShopService();
	private ShopCategoryService categoryService = new ShopCategoryService();
	private ProductAttrService attrService = new ProductAttrService();


	public void delete(Product product) {
		productDao.del(product);
	}

	public void add(Product product, String attr, QualityExtend qualityExtend) throws ServiceException {
		product.setAddTime(new Date());
		if (product.getCategoryId() == 0) {
			throw new ServiceException("类别id不能为空!!!");
		}
		if (product.getShopId() == 0) {
			throw new ServiceException("商家id不能为空!!!");
		}
		ShopCategory category = categoryService.findById(product.getCategoryId());
		product.setCategoryName(category.getName());
		if (attr != null && !"".equals(attr)) {
			product.setHasAttribute(1);
		}
		Shop shop = shopService.findById(product.getShopId());
		product.setShopName(shop.getShopName());
		Integer productId = productDao.addProduct(product);
		if (attr != null && !"".equals(attr)) {
			String[] attrs = attr.split("-");
			ProductAttr productAttr = null;
			for (String a : attrs) {
				String[] value = a.split(",");
				productAttr = new ProductAttr();
				productAttr.setAttrId(Integer.valueOf(value[0]));
				productAttr.setAttrValue(value[1]);
				productAttr.setCount(Integer.valueOf(value[2]));
				productAttr.setPrice(new BigDecimal(value[3]));
				productAttr.setProductId(productId);
				productAttr.setAttrName(CacheManage.mapAttrs.get(Integer.valueOf(value[0])).getAttrName());
				if (attrService.isExit(productAttr) == null) {
					attrService.add(productAttr);
				}
			}
		}
		if ("1".equals(product.getIsQuality())) {
			Assert.notNull(qualityExtend, "精品（周套餐）,商品的额外参数不能为空");
			Assert.hasText(qualityExtend.getSendDate(), "精品（周套餐）,商品的额外参数: 配送日期  不能为空");
			Assert.hasText(qualityExtend.getQualityimage(), "精品（周套餐）,商品的额外参数: 小图 不能为空");
			Assert.hasText(qualityExtend.getQualitybigImage(), "精品（周套餐）,商品的额外参数: 大图  不能为空");
			Assert.hasText(qualityExtend.getQualitytimeOutImage(), "精品（周套餐）,商品的额外参数: 过期图  不能为空");
			
			remoteService.addQualityExtend(qualityExtend, shop.getCityId(), productId);
		}
	}

	public void update(Product product, String attr, QualityExtend qualityExtend) throws ServiceException {
		product.setAddTime(new Date());
		if (product.getCategoryId() == 0) {
			throw new ServiceException("类别id不能为空!!!");
		}
		if (product.getShopId() == 0) {
			throw new ServiceException("商家id不能为空!!!");
		}
		ShopCategory category = categoryService.findById(product.getCategoryId());
		product.setCategoryName(category.getName());
		if (attr != null && !"".equals(attr)) {
			product.setHasAttribute(1);
		}
		Shop shop = shopService.findById(product.getShopId());
		Product oldProduct = findById(product.getId());
		product.setShopName(shop.getShopName());
		try {
			BeanUtils.copyProperties(oldProduct, product);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		productDao.update(oldProduct);
		if (attr != null && !"".equals(attr)) {
			attrService.deleteAttrByProductId(product.getId());
			String[] attrs = attr.split("-");
			ProductAttr productAttr = null;
			for (String a : attrs) {
				String[] value = a.split(",");
				productAttr = new ProductAttr();
				productAttr.setAttrId(Integer.valueOf(value[0]));
				productAttr.setAttrValue(value[1]);
				productAttr.setCount(Integer.valueOf(value[2]));
				productAttr.setPrice(new BigDecimal(value[3]));

				productAttr.setProductId(product.getId());
				productAttr.setAttrName(CacheManage.mapAttrs.get(Integer.valueOf(value[0])).getAttrName());
				if (attrService.isExit(productAttr) == null) {
					attrService.add(productAttr);
				}
			}
		}
		
		if ("1".equals(product.getIsQuality())) {
			Assert.notNull(qualityExtend, "精品（周套餐）,商品的额外参数不能为空");
			Assert.hasText(qualityExtend.getSendDate(), "精品（周套餐）,商品的额外参数: 配送日期  不能为空");
			Assert.hasText(qualityExtend.getQualityimage(), "精品（周套餐）,商品的额外参数: 小图 不能为空");
			Assert.hasText(qualityExtend.getQualitybigImage(), "精品（周套餐）,商品的额外参数: 大图  不能为空");
			Assert.hasText(qualityExtend.getQualitytimeOutImage(), "精品（周套餐）,商品的额外参数: 过期图  不能为空");
			
			remoteService.updateQualityExtend(qualityExtend, shop.getCityId(), product.getId());
		}
	}

	public List<Product> findAll(Map<String, Object> params) {
		List<Product> data = productDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return productDao.count(params);
	}

	public Product findById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return productDao.findOne(params);
	}

	public ResultProduct findByIdAndAttr(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		ResultProduct resultProduct = new ResultProduct();
		Product product = productDao.findOne(params);

		if (product != null) {
			try {
				BeanUtils.copyProperties(resultProduct, product);
				resultProduct.setAttrs(attrService.findByProductId(product.getId()));
				if ("1".equals(product.getIsQuality())) {
					QualityExtend qualityExtend = remoteService.getQualityExtend(Long.valueOf(product.getId()));
//			    	Assert.notNull(qualityExtend, "获取精品（周套餐）,商品的额外参数异常");
//					Assert.hasText(qualityExtend.getSendDate(), "获取精品（周套餐）,商品的额外参数异常: 配送日期  为空");
//					Assert.hasText(qualityExtend.getQualityimage(), "获取精品（周套餐）,商品的额外参数异常: 小图 为空");
//					Assert.hasText(qualityExtend.getQualitybigImage(), "获取精品（周套餐）,商品的额外参数异常: 大图  为空");
//					Assert.hasText(qualityExtend.getQualitytimeOutImage(), "获取精品（周套餐）,商品的额外参数异常: 过期图  为空");
					if (qualityExtend != null) {
						BeanUtils.copyProperties(resultProduct, qualityExtend);
					}
				}
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}

		return resultProduct;
	}

	public void setProductState(Product product) {
		productDao.setProductState(product);
	}

	public ArrayList<ProductResult> findByShopId(Integer shopId) {
		ArrayList<ProductResult> data = new ArrayList<>();
		ProductResult result = null;
		Shop shop = shopService.findById(shopId);
		if ("zhoutaocan".equals(shop.getShowLableCode())) {
			Calendar now = Calendar.getInstance();
			int week = now.get(Calendar.DAY_OF_WEEK);
			int sort_b = 0;
			int sort_e = 0;
			if (week == Calendar.SUNDAY || week == Calendar.SATURDAY) {
				// 周六周日
				sort_b = 6;
				sort_e = 10;
			} else {
				sort_b = week;
				sort_e = 10;
			}
			List<com.zaofan.mobile.bean.Product> p;
			List<ShopCategory> categories = categoryService.findByShopIdAndSort(shop.getId(), sort_b, sort_e);
			if (categories != null && categories.size() > 0) {
				int index = sort_b;
				for (ShopCategory category : categories) {
					if ((index - 1) == 5) {
						now.add(Calendar.DATE, 1);
						result = new ProductResult();
						result.setCategoryId(0);
						result.setCategoryName("周六");
						result.setDate(now.get(Calendar.YEAR) + "-" + to2Num(now.get(Calendar.MONTH) + 1) + "-"
								+ to2Num(now.get(Calendar.DATE)));
						result.setProducts(Collections.EMPTY_LIST);
						data.add(result);
						now.add(Calendar.DATE, 1);
						result = new ProductResult();
						result.setCategoryId(0);
						result.setCategoryName("周日");
						result.setDate(now.get(Calendar.YEAR) + "-" + to2Num(now.get(Calendar.MONTH) + 1) + "-"
								+ to2Num(now.get(Calendar.DATE)));
						result.setProducts(Collections.EMPTY_LIST);
						data.add(result);
					}
					now.add(Calendar.DATE, 1);
					p = findByCategoryId(category.getId());
					if (p != null && p.size() > 0) {
						result = new ProductResult();
						result.setCategoryId(category.getId());
						result.setCategoryName(category.getName().replace("下", ""));
						result.setDate(now.get(Calendar.YEAR) + "-" + to2Num(now.get(Calendar.MONTH) + 1) + "-"
								+ to2Num(now.get(Calendar.DATE)));
						result.setProducts(p);
						data.add(result);
					}
					index++;
				}
			}
			return data;
		}
		List<com.zaofan.mobile.bean.Product> p;
		List<ShopCategory> categories = categoryService.findByShopId(shop.getId());
		if (categories != null && categories.size() > 0) {
			for (ShopCategory category : categories) {
				p = findByCategoryId(category.getId());
				if (p != null && p.size() > 0) {
					result = new ProductResult();
					result.setCategoryId(category.getId());
					result.setCategoryName(category.getName());
					result.setProducts(p);
					data.add(result);
				}
			}
		}
		return data;
	}

	public String to2Num(int num) {
		if (num < 10) {
			return "0" + num;
		}
		return num + "";
	}

	public Long countByShopId(int shopId) {
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<com.zaofan.mobile.bean.Product> findByCategoryId(int categoryId) {
		Map<String, Object> params = new HashMap<>();
		params.put("categoryId", categoryId);
		params.put("state", StateConstant.STATE_SHOW);
		List<Product> temp = findAll(params);
		try {
			if (temp.size() > 0) {
				List<com.zaofan.mobile.bean.Product> products = new ArrayList<>();
				com.zaofan.mobile.bean.Product product;
				Map<String, List<ProductAttr>> attribute;
				for (Product p : temp) {
					product = new com.zaofan.mobile.bean.Product();
					BeanUtils.copyProperties(product, p);
					if (p.getHasAttribute() == 1) {
						List<ProductAttr> attrs = attrService.findByProductId(p.getId());
						attribute = new HashMap<String, List<ProductAttr>>();
						for (ProductAttr attr : attrs) {
							if (attribute.containsKey(attr.getAttrName())) {
								List<ProductAttr> item = attribute.get(attr.getAttrName());
								if (item == null) {
									item = new ArrayList<>();
								}
								item.add(attr);
							} else {
								List<ProductAttr> item = new ArrayList<>();
								item.add(attr);
								attribute.put(attr.getAttrName(), item);
							}
						}
						String ids = "";
						for (Map.Entry<String, List<ProductAttr>> entry : attribute.entrySet()) {
							for (ProductAttr attr : entry.getValue()) {
								ids += attr.getId() + ",";
							}
							ids = ids.substring(0, ids.length() - 1);
							ids += "==";
						}
						List<com.zaofan.mobile.bean.ProductAttr> newAttr = new ArrayList<>();
						if (!"".equals(ids)) {
							ids = ids.substring(0, ids.length() - 2);
							List<String> com = descartes(ids);
							// System.err.println(com);
							com.zaofan.mobile.bean.ProductAttr attr;
							for (String string : com) {
								String id1 = string.split(",")[0];
								String id2 = string.split(",")[1];
								ProductAttr productAttr1 = attrService.findById(Integer.valueOf(id1));
								ProductAttr productAttr2 = attrService.findById(Integer.valueOf(id2));
								attr = new com.zaofan.mobile.bean.ProductAttr();
								attr.setAttrId(string);
								attr.setAttrValue(productAttr1.getAttrValue() + "/" + productAttr2.getAttrValue());
								attr.setPrice(product.getPrice().add(productAttr1.getPrice()).add(productAttr2.getPrice()));
								newAttr.add(attr);
							}
						}
						product.setAttribute(newAttr);
					}
					product.setImage(UrlConstant.HOST_URL + product.getImage());
					product.setBigImage(UrlConstant.HOST_URL + product.getBigImage());
					products.add(product);
				}
				return products;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Collections.EMPTY_LIST;
	}

	public static List<String> descartes(String str) {
		String[] list = str.split("==");
		List<List> strs = new ArrayList<List>();
		for (int i = 0; i < list.length; i++) {
			strs.add(Arrays.asList(list[i].split(",")));
		}
		int total = 1;
		for (int i = 0; i < strs.size(); i++) {
			total *= strs.get(i).size();
		}
		String[] mysesult = new String[total];
		int now = 1;
		// 每个元素每次循环打印个数
		int itemLoopNum = 1;
		// 每个元素循环的总次数
		int loopPerItem = 1;
		for (int i = 0; i < strs.size(); i++) {
			List temp = strs.get(i);
			now = now * temp.size();
			// 目标数组的索引值
			int index = 0;
			int currentSize = temp.size();
			itemLoopNum = total / now;
			loopPerItem = total / (itemLoopNum * currentSize);
			int myindex = 0;
			for (int j = 0; j < temp.size(); j++) {

				// 每个元素循环的总次数
				for (int k = 0; k < loopPerItem; k++) {
					if (myindex == temp.size())
						myindex = 0;
					// 每个元素每次循环打印个数
					for (int m = 0; m < itemLoopNum; m++) {
						mysesult[index] = (mysesult[index] == null ? "" : mysesult[index] + ",")
								+ ((String) temp.get(myindex));
						index++;
					}
					myindex++;

				}
			}
		}
		return Arrays.asList(mysesult);
	}

	public void updateDateSellCount() {
		productDao.updateDateSellCount();
	}

	public static void main(String[] args) {
		// Calendar now = Calendar.getInstance();
		// int year = now.get(Calendar.YEAR);
		// int month = now.get(Calendar.MONTH) + 1;
		// int day = now.get(Calendar.DAY_OF_MONTH);
		// int hour = now.get(Calendar.HOUR_OF_DAY);
		// int minute = now.get(Calendar.MINUTE);
		// int second = now.get(Calendar.SECOND);
		// System.err.println(hour + "-" + minute + "-" + second);
		ProductService productService = new ProductService();
		System.err.println(new Gson().toJson(productService.getWeekProducts()));
	}

	public ArrayList<ProductResultV2> getWeekProducts() {
		ArrayList<ProductResultV2> data = new ArrayList<>();
		try {
			Shop shop = shopService.getPackageShop("zhoutaocan");
			if (shop != null) {
				Calendar now = Calendar.getInstance();
				int week = now.get(Calendar.DAY_OF_WEEK);
				int sort_b = 0;
				int sort_e = 0;
				if (week == Calendar.SUNDAY || week == Calendar.SATURDAY) {
					// 周六周日
					sort_b = 1;
					sort_e = 5;
				} else if (week == Calendar.FRIDAY) {
					sort_b = 6;
					sort_e = 10;
				} else {
					sort_b = week;
					sort_e = 5;
				}
				if (week == Calendar.FRIDAY) {
					now.add(Calendar.DATE, 2);
				}
				if (week == Calendar.SATURDAY) {
					now.add(Calendar.DATE, 1);
				}
				List<Product> products = productDao.getWeekProducts(shop, sort_b, sort_e);
				ProductResultV2 item;
				com.zaofan.mobile.bean.Product productVo;
				for (Product product : products) {
					now.add(Calendar.DATE, 1);
					productVo = new com.zaofan.mobile.bean.Product();
					BeanUtils.copyProperties(productVo, product);
					productVo.setImage(UrlConstant.HOST_URL + productVo.getImage());
					productVo.setBigImage(UrlConstant.HOST_URL + productVo.getBigImage());
					item = new ProductResultV2();
					item.setProduct(productVo);
					item.setCategoryId(product.getCategoryId());
					item.setCategoryName(product.getCategoryName().replace("下", ""));
					item.setDate(now.get(Calendar.YEAR) + "-" + to2Num(now.get(Calendar.MONTH) + 1) + "-"
							+ to2Num(now.get(Calendar.DATE)));
					data.add(item);
				}
				//2016 年端午，周日，临时代码， 节后删,begin
				Calendar now1 = Calendar.getInstance();
				Calendar duanwu = Calendar.getInstance();
				duanwu.set(2016, 5, 12, 8, 0, 0);
				System.err.println("duanwu-------------------");
				if (now1.before(duanwu)) {
					List<Product> products1 = productDao.getWeekProducts(shop, 700, 700);
					System.err.println("products1: "+products1.size());
					if (products1.size() > 0) {
						productVo = new com.zaofan.mobile.bean.Product();
						BeanUtils.copyProperties(productVo, products1.get(0));
						productVo.setImage(UrlConstant.HOST_URL + productVo.getImage());
						productVo.setBigImage(UrlConstant.HOST_URL + productVo.getBigImage());
						item = new ProductResultV2();
						item.setProduct(productVo);
						item.setCategoryId(products1.get(0).getCategoryId());
						item.setCategoryName(products1.get(0).getCategoryName().replace("下", ""));
						item.setDate("2016-06-12");
						data.add(item);
					}
				}
				//2016 年端午，周日，临时代码， 节后删,end
				return data;
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return data;
	}

	public ArrayList<ProductResultV2> getWeekProductsTwo() {
		ArrayList<ProductResultV2> data = new ArrayList<>();
		try {
			Shop shop = shopService.getPackageShop("zhoutaocan");
			if (shop != null) {
				Calendar now = Calendar.getInstance();
				int week = now.get(Calendar.DAY_OF_WEEK);
				int sort_b = 0;
				int sort_e = 0;
				List<Product> timeOutProducts;
				com.zaofan.mobile.bean.Product productVo;
				ProductResultV2 item;
				if (week == Calendar.SUNDAY || week == Calendar.SATURDAY) {
					// 周六周日
					sort_b = 1;
					sort_e = 5;
				} else if (week == Calendar.FRIDAY) {
					sort_b = 6;
					sort_e = 10;
				} else {
					sort_b = week;
					sort_e = 5;
					if (week > 1) {
						timeOutProducts = productDao.getWeekProducts(shop, 1, week - 1);
						if (timeOutProducts != null && timeOutProducts.size() > 0) {
							for (Product product : timeOutProducts) {
								productVo = new com.zaofan.mobile.bean.Product();
								BeanUtils.copyProperties(productVo, product);
								productVo.setIsExprice(1);
								productVo.setImage(UrlConstant.HOST_URL + product.getTimeOutImage());
								productVo.setBigImage(UrlConstant.HOST_URL + productVo.getBigImage());
								item = new ProductResultV2();
								item.setProduct(productVo);
								item.setCategoryId(product.getCategoryId());
								item.setCategoryName(product.getCategoryName().replace("下", ""));
								item.setDate("");
								data.add(item);
							}
						}
					}

				}
				if (week == Calendar.FRIDAY) {
					now.add(Calendar.DATE, 2);
				}
				if (week == Calendar.SATURDAY) {
					now.add(Calendar.DATE, 1);
				}
				List<Product> products = productDao.getWeekProducts(shop, sort_b, sort_e);

				for (Product product : products) {
					now.add(Calendar.DATE, 1);
					productVo = new com.zaofan.mobile.bean.Product();
					BeanUtils.copyProperties(productVo, product);
					productVo.setImage(UrlConstant.HOST_URL + productVo.getImage());
					productVo.setBigImage(UrlConstant.HOST_URL + productVo.getBigImage());
					item = new ProductResultV2();
					item.setProduct(productVo);
					item.setCategoryId(product.getCategoryId());
					item.setCategoryName(product.getCategoryName().replace("下", ""));
					item.setDate(now.get(Calendar.YEAR) + "-" + to2Num(now.get(Calendar.MONTH) + 1) + "-"
							+ to2Num(now.get(Calendar.DATE)));
					data.add(item);
				}
				return data;
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return data;
	}

	/**
	 * 查找本周热卖商品
	 */
	public List<Product> findHotProduct(String cityId,int page){
		return productDao.findHotProduct(cityId,page);
	}

	/**
	 * 查找所有热卖商品
	 * @param cityId
	 * @return
     */
	public List<Product> findAllHotProduct(String cityId,String begin,String end) {
		return productDao.findAllHotProduct(cityId,begin,end);
	}

	public List<Product> findNewProduct(String cityId) {
		return productDao.findNewProduct(cityId);
	}
}
